package com.util.thred;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.*;

/**
 * @Description: TODO
 * @Author: hechaobo
 * @Date: 2024/5/17
 **/
@Slf4j
@Data
public class ThreadUtil {
    ThreadPoolExecutor executor;
    Semaphore semaphore;
   public ThreadUtil(int maxThread){
        executor = new ThreadPoolExecutor(maxThread,maxThread,1, TimeUnit.MINUTES,
               new LinkedBlockingQueue<>());
        semaphore=new Semaphore(maxThread);

   }
   public void doWork(Runnable runnable){
       try {
           semaphore.acquire();
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       executor.execute(()->{
           runnable.run();
           semaphore.release();
       });
   }
   public void shutdown(){
       executor.shutdown();
       log.info("关闭线程池");
   }
   public static void runWorks(List<Runnable> runnables){
       int size = runnables.size();
       CountDownLatch countDownLatch=new CountDownLatch(size);
       for (Runnable runnable : runnables) {
           new Thread(()->{
               runnable.run();
               countDownLatch.countDown();
           }).start();
       }
       try {
           countDownLatch.await();
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
   }
}
